package json;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 *
 * @author dakhoa
 * @version 1.0
 */
public class JsonArray {

    private Set<AbstractJsonObject> elements;
    private String name = "elements";

    public JsonArray(String name) {
        elements = new HashSet<AbstractJsonObject>();
        if (name != null) {
            this.name = name;
        }
    }

    public void add(Collection<? extends AbstractJsonObject> jsons) {
        elements.addAll(jsons);
    }

    public void add(AbstractJsonObject... jsons) {
        for (AbstractJsonObject element : jsons) {
            add(element);
        }
    }

    public JsonArray add(AbstractJsonObject element) {
        if (elements.contains(element)) {
            elements.remove(element);
        }

        elements.add(element);
        return this;
    }

    public boolean remove(AbstractJsonObject element) {
        return elements.remove(element);
    }

    public String toJson() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("{\"" + name + "\":[");

        for (AbstractJsonObject e : elements) {
            stringBuilder.append(e.toJson()).append(",");
        }

        stringBuilder.append("]}");

        return stringBuilder.toString();
    }
}
